#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sublime
import random
import hashlib
import urllib
import json
from .. import Common

template = '''
<body>
	<style>
		body {font-family: sans-serif;}
		h1 {font-size: 1.1rem;font-weight: bold;margin: 0 0 0.25em 0;}
		p {font-size: 1.05rem;margin: 0;}
	</style>
	<h1>%s</h1>
	<div>%s</div>
</body>
'''

def translateYoudao(text):
	appKey = '075aa28fd372d61b'
	secretKey = 'dse5SgFXbSNfkq3PrQhzeSlH0birnloZ'
	salt = str(random.randint(1, 65536))
	sign = appKey + text + salt + secretKey
	sign = hashlib.md5(sign.encode('utf-8')).hexdigest()

	data = {}
	data['q'] = text
	data['appKey'] = appKey
	data['salt'] = salt
	data['sign'] = sign
	data['from'] = 'auto'
	data['to'] = 'auto'
	data = urllib.parse.urlencode(data).encode('utf-8')

	content = urllib.request.urlopen('https://openapi.youdao.com/api', data).read().decode('utf-8')
	return json.loads(content)

def run():
	text = Common.getText()
	try:
		data = translateYoudao(text)
		if 'basic' in data and 'explains' in data['basic']:
			explains = data['basic']['explains']
		elif 'translation' in data:
			explains = data['translation']
		else:
			explains = ['未找到释义']

		result = ''
		for explain in explains:
			result = result + '<p>%s</p>' % explain
	except Exception as e:
		result = '发生了一些错误'

	view = sublime.active_window().active_view()
	view.show_popup(template % (text, result), flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=-1, max_width=1024)
